package com.fwx.chatroom.controller;
import com.fwx.chatroom.model.User;
import com.fwx.chatroom.mapper.UserMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
public class UserController {

    @Autowired
    UserMapper userMapper;

    @PostMapping("/login")
    @ResponseBody
    public Object login(String username,String password, HttpServletRequest request) {
        User user = userMapper.selectByName(username);
        //账户 || 密码不匹配
        if(user == null || !user.getPassword().equals(password)) {
            log.info("接收的参数:username: "+username+" password: "+password);
            log.info("登录失败!用户名或密码错误!user="+user);
            return new User();
        }
        //账号密码匹配
        HttpSession session =  request.getSession(true);
        session.setAttribute("user",user);
        user.setPassword("");
        return user;
    }

    @PostMapping("/register")
    @ResponseBody
    public Object register(String username, String password) {
        User user = null;
        try {
            user = new User();
            user.setUsername(username);
            user.setPassword(password);
            int ret = userMapper.insert(user);
            user.setPassword("");
            log.info("注册成功！");
        }catch (DuplicateKeyException e){
            //抛出异常，名字错误，注册失败
            log.info("名字重复，注册失败");
            user = new User();
        }
        return user;
    }
    @GetMapping("/userInfo")
    @ResponseBody
    public Object getUserInfo(HttpServletRequest request) {
        //1.从请求中获取会话
        HttpSession session = request.getSession(false);
        if(session == null) {
            log.info("当前获取不到session");
            return new User();
        }
        //2.从会话中获取到之前保存的用户对象
        User user = (User) session.getAttribute("user");
        if(user == null) {
            log.info("获取不到user对象");
            return new User();
        }
        user.setPassword("");
        return user;
    }
}
